<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发生日期" prop="caseDate">
        <el-date-picker clearable
            v-model="queryParams.caseDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发生日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="发生地点" prop="site">
        <el-input
          v-model="queryParams.site"
          placeholder="请输入发生地点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="方向" prop="direction">
        <el-input
          v-model="queryParams.direction"
          placeholder="请输入方向"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="里程" prop="mileage">
        <el-input
          v-model="queryParams.mileage"
          placeholder="请输入里程"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div style="display: flex;">
      <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click.native="handleAdd"
        >新增
        </el-button>
      
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
     

      
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入
        </el-button>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </div>
        
      
      

    <el-table
      v-loading="loading"
      :data="caseList"
      @selection-change="handleSelectionChange"
      :span-method="objectSpanMethod"
      border>
<!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" width="50" align="center">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column label="发生日期" align="center" prop="caseDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.caseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发生地点" align="center" prop="site" width="200"/>
      <el-table-column label="方向" align="center" prop="direction"/>
      <el-table-column label="里程" align="center" prop="mileage"/>
      <el-table-column label="发生原因" align="center" prop="caseCause"/>
      <el-table-column label="受损项目" align="center" prop="damageName"/>
      <el-table-column label="单位" align="center" prop="damageUnit"/>
      <el-table-column label="受损数量" align="center" prop="damageAmount"/>
      <el-table-column label="受损单价" align="center" prop="damageUnitPrice"/>

      <el-table-column label="受损金额" align="center" prop="damagePrice"/>
      <el-table-column label="受损合计" align="center" prop="damageTotal"/>
      <el-table-column label="现场勘察情况" align="center" prop="siteSituation" width="100"/>
      <el-table-column label="核损数量" align="center" prop="lossAmount"/>
      <el-table-column label="核损单价" align="center" prop="lossUnitPrice"/>
      <el-table-column label="核损金额" align="center" prop="lossPrice"/>
      <el-table-column label="核损合计" align="center" prop="lossTotal"/>
      <el-table-column label="免赔金额" align="center" prop="deductibleAmount"/>
      <el-table-column label="理算金额" align="center" prop="adjustedAmount"/>
      <el-table-column label="备注" align="center" prop="remark"  width="200"/>

      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="70">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['business:case:edit']"-->
<!--          >修改-->
<!--          </el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:case:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改案件记录信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发生日期" prop="caseDate">
          <el-date-picker clearable
                          v-model="form.caseDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择发生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发生地点" prop="site">
          <el-input v-model="form.site" placeholder="请输入发生地点"/>
        </el-form-item>
        <el-form-item label="方向" prop="direction">
          <el-input v-model="form.direction" placeholder="请输入方向"/>
        </el-form-item>
        <el-form-item label="里程" prop="mileage">
          <el-input v-model="form.mileage" placeholder="请输入里程"/>
        </el-form-item>
        <el-form-item label="发生原因" prop="caseCause">
          <el-input v-model="form.caseCause" placeholder="请输入发生原因"/>
        </el-form-item>
        <el-form-item label="受损合计" prop="damageTotal">
          <el-input v-model="form.damageTotal" placeholder="请输入受损合计"/>
        </el-form-item>
        <el-form-item label="核损合计" prop="lossTotal">
          <el-input v-model="form.lossTotal" placeholder="请输入核损合计"/>
        </el-form-item>
        <el-form-item label="免赔金额" prop="deductibleAmount">
          <el-input v-model="form.deductibleAmount" placeholder="请输入免赔金额"/>
        </el-form-item>
        <el-form-item label="理算金额" prop="adjustedAmount">
          <el-input v-model="form.adjustedAmount" placeholder="请输入理算金额"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 数据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的人员数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // import {listCase, getCase, delCase, addCase, updateCase} from "@/api/business/case";
  // import {getToken} from "@/utils/auth";
  import {
    parseTime
  } from '@/utils/ruoyi.js'
  import pagination from '@/views/components/pagination'
  import rightToolbar from '@/views/components/rightToolbar'
  import { req } from './req';
  export default {
    name: "Case",
    components:{pagination,
      rightToolbar
    },
    
    data() {
      return {
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 案件记录信息表格数据
        caseList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          caseDate: null,
          site: null,
          direction: null,
          mileage: null,
          caseCause: null,
          damageTotal: null,
          lossTotal: null,
          deductibleAmount: null,
          adjustedAmount: null,
          isDelete: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        // 用户导入参数
        upload: {
          // 是否显示弹出层（人员导入）
          open: false,
          // 弹出层标题（人员导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的人员数据
          updateSupport: 0,
          // 设置上传的请求头部
          // headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/business/case/importData"
        },
        req:[]
      };
    },
    created() {
      this.getList();

    },
    methods: {
      /** 查询案件记录信息列表 */
      getList() {
        // this.loading = true;
        // listCase(this.queryParams).then(response => {
        //   this.req = response.rows;
        //   this.total = response.total;
        //   this.loading = false;
        //   console.log(this.req );
        //   let that=this;
        //   let result = that.req.map((Item) => {
        //     return Item.detailList.map((item) => {
        //       return {

        //         caseId: Item.caseId,
        //         caseDate: Item.caseDate,
        //         site: Item.site,
        //         direction: Item.direction,
        //         mileage: Item.mileage,
        //         caseCause: Item.caseCause,
        //         damageTotal: Item.damageTotal,
        //         lossTotal: Item.lossTotal,
        //         deductibleAmount: Item.deductibleAmount,
        //         adjustedAmount: Item.adjustedAmount,
        //         ...item  // 展开每个 detailList 项的数据
        //       };
        //     });
        //   }).flat();
        //   console.log(result);

        //   this.caseList = result
        // });
        
        // let result = req.map((Item) => {
        //   return Item.detailList.map((item) => {
        //     let length = Item.detailList.length
        //     return {
        //       length : length,
        //       caseId: Item.caseId,
        //       caseDate: Item.caseDate,
        //       site: Item.site,
        //       direction: Item.direction,
        //       mileage: Item.mileage,
        //       caseCause: Item.caseCause,
        //       damageTotal: Item.damageTotal,
        //       lossTotal: Item.lossTotal,
        //       deductibleAmount: Item.deductibleAmount,
        //       adjustedAmount: Item.adjustedAmount,
        //       ...item  // 展开每个 detailList 项的数据
        //     };
        //   });
        // }).flat(); 
        // console.log(result);
        
        // this.caseList = result

      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          caseId: null,
          caseDate: null,
          site: null,
          direction: null,
          mileage: null,
          caseCause: null,
          damageTotal: null,
          lossTotal: null,
          deductibleAmount: null,
          adjustedAmount: null,
          isDelete: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        console.log();
        
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.caseId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加案件记录信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const caseId = row.caseId || this.ids
        getCase(caseId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改案件记录信息";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.caseId != null) {
              updateCase(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCase(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const caseIds = row.caseId || this.ids;
        this.$modal.confirm('是否确认删除案件记录信息编号为"' + caseIds + '"的数据项？').then(function () {
          return delCase(caseIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        console.log(123);

        this.download('business/case/export', {
          ...this.queryParams
        }, `case_${new Date().getTime()}.xlsx`)
      },
      /** 导入按钮操作 */
      handleImport() {
        
        this.upload.title = "数据导入";
        this.upload.open = true;
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
        this.getList();
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('business/case/importTemplate', {}, `数据导入模板.xlsx`)
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      //表单处理
      objectSpanMethod({ row, column, rowIndex, columnIndex }){
        // //找到第一个列表length数据
        // let x = 0
        // //计算到该某行开始数据合并
        // let y = 0
        // if(rowIndex === x){
        //   if(row.length != 1){
        //     let mergeIndex = y
        //     if(rowIndex === mergeIndex && columnIndex === 1){
        //       return [row.length, 1]
        //     }
        //     for(let i = mergeIndex;i < mergeIndex + row.length;i++){
        //       if(rowIndex === i && columnIndex === 1){
        //         console.log(index);
                
        //         return [0,0]
        //       }
        //     }
        //   }
        //   else{
        //     y++
        //   }

        //判断到哪一行数据
        let x = 0;
        const req = this.req;

        for (let i = 0; i < req.length; i++) {
          if (req[i].detailList.length !== 1) {
            if (
              (columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 ||
                columnIndex === 5 || columnIndex === 6 || columnIndex === 11 || columnIndex === 13 ||
                columnIndex === 14 || columnIndex === 15) && rowIndex === x
            ) {
              return [req[i].detailList.length, 1];
            }

            for (let I = x; I < x + req[i].detailList.length; I++) {
              if (
                (columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 ||
                  columnIndex === 5 || columnIndex === 6 || columnIndex === 11 || columnIndex === 13 ||
                  columnIndex === 14 || columnIndex === 15) && rowIndex === I
              ) {
                return [0, 0]; 
              }
            }
            x += req[i].detailList.length;
          } else {
            x++;
          }
        }
        
        
      },
      parseTime
    }
  };
</script>

<style lang="scss" scoped>
  .el-upload {
      display: inline-block;
      text-align: center;
      cursor: pointer;
      outline: none;
  }
</style>
